#include "qwtAreaChart.h"
#include <QVector>
#include <QMessageBox>
#include <cstdlib>
#include <time.h>
#include "../../../../gui/AreaChartGUI/AreaChartLegend.h"

namespace LightChart
{
    void qwtAreaChart::draw() {}
    void qwtAreaChart::preparePlot(QwtPlot* plot)
    {
	try
	{
	    /*plot settings */
	    plot->setAutoReplot(true);
	    plot->enableAxis(QwtPlot::xBottom,false);
	    plot->setTitle(chart.get_title().c_str());
	    //plot->setFixedSize(chart.getWindowWidth(),chart.getWindowHeight());
	    const std::vector<Axis*>& axisptr = chart.get_axes();
	    plot->setAxisTitle(QwtPlot::xBottom,QString(axisptr[0]->get_label().c_str()));
	    plot->setAxisTitle(QwtPlot::yLeft,QString(axisptr[1]->get_label().c_str()));
	    plot->setAxisScale(QwtPlot::xBottom,0,1,1);
	    plot->setAxisScale(QwtPlot::yLeft,0,100,5);

	    /* curve settings */
	    QVector<QwtPlotCurve*> curves;
	    std::vector<QColor> colors;
	    colors.push_back(Qt::red);
	    colors.push_back(Qt::blue);
	    colors.push_back(Qt::green);
	    srand(time(NULL));
	    const std::vector<unsigned short int>& contribution = dynamic_cast<BasicAreaChart&>(chart).get_contribution();
	    if(contribution.empty()) throw QuietStop();
	    double x_axis[2] = {0., 1.};
	    unsigned short int max = 100;
	    for(unsigned int i = 0; i < contribution.size() - 1; ++i)
	    {
		double* tmp = new double[2]; //Fix this. Causes memory leaks
		max -= contribution[i];
		tmp[0] = tmp[1] = max;
		QwtPlotCurve* curve = new QwtPlotCurve(); //Fix. Not freed
		if(i >= 3) colors.push_back(QColor(rand() % 256, rand() % 256, rand() % 256));
		curve->setBrush(QBrush(colors[i]));
		curve->setRenderHint(QwtPlotCurve::RenderAntialiased);
		curve->setSamples(x_axis,tmp,2);
		curves.push_back(curve);
	    }

	    /* legend's settings */
	    std::map<Axis*, std::vector<Series*> >& axes = Storage::get_instance().charts[&chart];
	    std::vector<Series*>& series_l = axes[axisptr[1]];
	    if(series_l.size() > 1) throw std::runtime_error("Assigning more than one data series to the labels' axis is pointless. Chart will be "
							     "plotted using only those data series that were assigned first.");
	    if(!series_l.empty())
	    {
		Series* lab = series_l.front();
		if(lab->get_type() != S_TEXT)
		    throw std::runtime_error("Data series assigned to labels' axis must be text. Chart will not be plotted.");
		qwtAreaChartLegend* legend = new qwtAreaChartLegend(&colors,&lab->get_string_vector(),0); //another leak to fix
		////legend->show();
		plot->insertLegend(legend,QwtPlot::RightLegend);
	    }

	    /* plotting */
	    for(QwtPlotCurve* curve : curves) curve->attach(plot);
	    plot->updateAxes();
	    plot->updateLayout();
	    plot->replot();
	}
	catch(const QuietStop&)
	{

	}
	catch(const std::runtime_error& e)
	{
	    QMessageBox::critical(0,"Error occured",e.what());
	}
    }
}